﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TasksUI
{
    public partial class Authors : Form
    {
        public Authors()
        {
            InitializeComponent();
        }

        public Authors(TasksModel.TaskLibrary library)
            : this()
        {
            lb.BeginUpdate();
            foreach (TasksModel.TaskAuthor ta in library.Authors)
                lb.Items.Add(ta);
            lb.EndUpdate();
        }

        public static void Show(TasksModel.TaskLibrary library)
        {
            using (Authors f = new Authors(library))
            {
                f.ShowDialog(Form.ActiveForm);
            }
        }

        private void lb_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lb.SelectedItem == null)
                return;
            TasksModel.TaskAuthor ta = (TasksModel.TaskAuthor)lb.SelectedItem;
            tbName.Text = ta.Name;
            tbName.Enabled = true;
            bSave.Enabled = true;
        }

        private void bSave_Click(object sender, EventArgs e)
        {
            string name = tbName.Text;
            TasksModel.TaskAuthor t = (TasksModel.TaskAuthor)lb.SelectedItem;

            foreach (TasksModel.TaskAuthor ta in lb.Items)
                if (ta.Name == name && ta.ID != t.ID)
                {
                    MessageBox.Show(this, "Author name already exists", "Save");
                    return;
                }
            tbName.Enabled = false;
            bSave.Enabled = false;
            t.SuspendChangedEvent();
            try
            {
                t.Name = name;
            }
            finally
            {
                t.ResumeChangedEvent();
            }
            tbName.Text = string.Empty;
            lb.Items[lb.SelectedIndex] = t;
        }
    }
}
